﻿using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using BrightIdeasSoftware;
using ROrganizer.UI.Controllers;
using ROrganizer.UI.Forms.Core;

namespace ROrganizer.UI.Forms
{
    internal partial class FolderManagerForm : Form
    {
        private readonly FolderManagerFormController controller;

        public FolderManagerForm()
        {
            this.controller = new FolderManagerFormController();
            this.InitializeComponent();

            this.chPath.AspectGetter = (AspectGetterDelegate)(x => x.ToString());

            this.olvFolders.Normalize();
            this.olvFolders.Objects = this.controller.Folders;
            this.olvFolders.Sort(this.chPath, SortOrder.Ascending);
            this.controller.Folders.CollectionChanged += this.OnChanged;
        }

        protected override void OnClosed(EventArgs e)
        {
            base.OnClosed(e);
            this.DialogResult = this.controller.IsChanged ? DialogResult.OK : DialogResult.Cancel;
        }

        private void OnChanged(object sender, NotifyCollectionChangedEventArgs e)
        {
            if (e.Action == NotifyCollectionChangedAction.Reset)
                this.olvFolders.ClearObjects();

            if (e.OldItems != null)
                this.olvFolders.RemoveObjects(e.OldItems);

            if (e.NewItems != null)
                this.olvFolders.AddObjects(e.NewItems);
        }

        private void OnAddFolder(object sender, EventArgs e)
        {
            this.ExecuteAndWatch(this.AddFolder);
        }

        private void AddFolder()
        {
            using (var dialog = new FolderBrowserDialog())
            {
                dialog.ShowNewFolderButton = false;
                dialog.Description = "Please select the folder containing multimedia files";

                if (dialog.ShowDialog(this) == DialogResult.OK)
                    this.controller.AddFolder(dialog.SelectedPath);
            }
        }

        private void OnRemoveFolder(object sender, EventArgs e)
        {
            this.ExecuteAndWatch(this.controller.RemoveFolders, this.olvFolders.SelectedObjects.OfType<string>().ToArray());
        }

        private void OnSelectionChanged(object sender, EventArgs e)
        {
            this.tsbRemove.Enabled = this.olvFolders.SelectedObjects.Count > 0;
        }
    }
}
